<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单号" prop="orderNumber">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="房间号" prop="roomNumber">
        <el-input
          v-model="queryParams.roomNumber"
          placeholder="请输入房间号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户姓名" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

       <el-form-item label="入住状态" prop="joinState">
          <el-select v-model="queryParams.joinState" placeholder="选择入住状态">
            <el-option v-for="dict in dict.type.join_state" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>

      <el-form-item label="手机号" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入手机号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="入住时间" prop="joinTime">
        <el-date-picker clearable
          v-model="queryParams.joinTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择入住时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="退房时间" prop="checkOutTime">
        <el-date-picker clearable
          v-model="queryParams.checkOutTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择退房时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['data:reserve:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['data:reserve:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['data:reserve:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['data:reserve:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reserveList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="reserveId" />
      <el-table-column label="订单号" align="center" prop="orderNumber" />
      <el-table-column label="房间号" align="center" prop="roomNumber" />
      <el-table-column label="客户姓名" align="center" prop="customerName" />

                 <el-table-column label="入住状态" align="center" prop="joinState">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.join_state" :value="scope.row.joinState">

          </dict-tag>
        </template>
      </el-table-column>

            <el-table-column label="性别" align="center" prop="gender">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.gender" :value="scope.row.gender">

          </dict-tag>
        </template>
      </el-table-column>
      <el-table-column label="手机号" align="center" prop="phoneNumber" />
      <el-table-column label="身份证" align="center" prop="idCard" />
      <el-table-column label="入住时间" align="center" prop="joinTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.joinTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="退房时间" align="center" prop="checkOutTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.checkOutTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['data:reserve:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['data:reserve:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改预定对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="房间号" prop="roomNumber">
        
           <el-select v-model="form.roomNumber" placeholder="请选择房间号" @change="getNo">
    <el-option
      v-for="item in roomNumberList"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
        </el-form-item>
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="form.customerName" placeholder="请输入客户姓名" />
        </el-form-item>
                        <el-form-item label="入住状态" prop="joinState">
          <el-select v-model="form.joinState" placeholder="选择入住状态">
            <el-option v-for="dict in dict.type.join_state" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
                <el-form-item label="性别" prop="gender">
          <el-select v-model="form.gender" placeholder="选择性别">
            <el-option v-for="dict in dict.type.gender" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNumber">
          <el-input v-model="form.phoneNumber" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="身份证" prop="idCard">
          <el-input v-model="form.idCard" type="text" placeholder="请输入身份证" />
        </el-form-item>
        <el-form-item label="入住时间" prop="joinTime">
          <el-date-picker clearable
            v-model="form.joinTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择入住时间"
            :picker-options="pickerOptions"
            :disabled="isRoomNumber"
            >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="退房时间" prop="checkOutTime">
          <el-date-picker clearable
            v-model="form.checkOutTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择退房时间"
             :picker-options="pickerOptions"
             :disabled="isRoomNumber"
            >
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listReserve, getReserve, delReserve, addReserve, updateReserve,queryAppointmentTime } from "@/api/data/reserve";
import { getAllRoomType } from "@/api/data/roomType";
import { getAllRoom} from '@/api/data/room'

export default {
  name: "Reserve",
   dicts: ['gender','join_state'],
  data() {
    return {
      //房间类型
      roomTypeList:[],
      // 房间号数据
      roomNumberList:[],
      // 房间列表
      roomList:[],
      //已被预约的房间
      roomNo:[],
      // 对日期可选参数
      isRoomNumber: true,
      // 禁用之前
           pickerOptions: {
                disabledDate: (time) => {
                
                   const today = new Date().toLocaleDateString();
                   //禁用这一天之前的日期
          let disable = time < new Date(today);
           //循环后端返回的数据，禁用时间大于joinTime小于checkOutTime，注意dayStart要减去一天，才能真正禁用dayStart这一天。
                        this.roomNo.forEach((item) => {
            disable =
              disable ||
              (time.getTime() > new Date(item.joinTime).getTime() - 8.64e7 &&
                time.getTime() < new Date(item.checkOutTime).getTime()); //减去一天8.64e7
          });
                    // return time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000; 
                    return disable
                },
            },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预定表格数据
      reserveList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNumber: null,
        roomNumber: null,
        customerName: null,
        joinState: null,
        gender: null,
        phoneNumber: null,
        idCard: null,
        joinTime: null,
        checkOutTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
          roomNumber: [
            { required: true, message: '请选择房间号', trigger: 'change' }
          ],
                    customerName: [
            { required: true, message: '请输入客户姓名', trigger: 'blur' }
          ],
           joinState: [
            { required: true, message: '请选择入住状态', trigger: 'change' }
          ],
           gender: [
            { required: true, message: '请选择性别', trigger: 'change' }
          ],
          phoneNumber: [
            { required: true, message: '请输入客户手机号', trigger: 'blur' }
          ],
           idCard: [
            { required: true, message: '请输入客户身份证', trigger: 'blur' }
          ],
            joinTime: [
            { required: true, message:  '请选择入住时间', trigger: 'blur' }
          ],
                      checkOutTime: [
            { required: true, message: '请选择退房时间', trigger: 'blur' }
          ],
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
   
          form: {
    handler(newVal) {
    
      if( newVal.roomNumber!=null&& newVal.roomNumber!='')
      {
         this.isRoomNumber=false
      }
      else{
        this.isRoomNumber = true
      }
    },
    deep: true // 深度监听(例如对象中的数据)
  }
  },
  methods: {
    // 禁用已被预约的日期
  async getNo() {
      this.form.joinTime = null
      this.form.checkOutTime = null
      let response = await queryAppointmentTime(this.form.roomNumber)
      this.roomNo = response.data
    },  
    /** 查询预定列表 */
    getList() {
      this.loading = true;
      listReserve(this.queryParams).then(response => {
        this.reserveList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        reserveId: null,
        orderNumber: null,
        roomNumber: null,
        customerName: null,
        joinState: null,
        gender: null,
        phoneNumber: null,
        idCard: null,
        joinTime: null,
        checkOutTime: null
      };
     
      this.roomList=[]
       this.roomNumberList=[]
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.reserveId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    async handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预定";
      // 获取房间列表数据
     await this.getAllRoomData()
    //  对房间列表数据进行处理
       this.roomListSelect()
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
        // 获取房间列表数据
     await this.getAllRoomData()
    //  对房间列表数据进行处理
        this.roomListSelect()
      const reserveId = row.reserveId || this.ids
      getReserve(reserveId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改预定";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.reserveId != null) {
            updateReserve(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addReserve(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const reserveIds = row.reserveId || this.ids;
      this.$modal.confirm('是否确认删除预定编号为"' + reserveIds + '"的数据项？').then(function() {
        return delReserve(reserveIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('data/reserve/export', {
        ...this.queryParams
      }, `reserve_${new Date().getTime()}.xlsx`)
    },
    // 房间列表数据
    async getAllRoomData(){
        let res = await getAllRoom()
       this.roomList = res.data
    },
    //对房间数组进行处理
     async roomListSelect(){
      var that = this
     let response = await getAllRoomType()
     this.roomTypeList = response.data
      this.roomList.map( (item)=>{
        var newObj={}
        newObj.value=item.roomNumber
        var data = that.roomList.find(ele=>{
            return ele.roomNumber===item.roomNumber
        })
        var result = that.roomTypeList.find(roomType=>{
          return roomType.roomTypeId === data.roomTypeId
        })
        newObj.label=item.roomNumber+'('+result.roomTypeName+')'
        that.roomNumberList.push(newObj)
      })
    }
  }
};
</script>
